package com.house365.core.view.pinned;

import java.util.Arrays;

import com.house365.core.constant.CorePreferences;

import android.util.Log;
import android.widget.SectionIndexer;
/**
 * 
 * @author py
 *	分组栏 与分组数据的关系
 */
public class MySectionIndexer implements SectionIndexer{
	private final String[] mSections;//
	private IndexerRanger[] mIndexerRangers;
	private final int[] mPositions;
	private final int mCount;
	private boolean buildedIdx = false;
	class IndexerRanger{
		public int start;
		public int end;
		
	}
	
	/**
	 * @param sections
	 * @param counts
	 */
	public MySectionIndexer(String[] sections, int[] counts) {
		if (sections == null || counts == null) {
			throw new NullPointerException();
		}
		if (sections.length != counts.length) {
			throw new IllegalArgumentException(
					"The sections and counts arrays must have the same length");
		}
		buildedIdx=false;
		this.mSections = sections;
		mPositions = new int[counts.length];
		mIndexerRangers = new IndexerRanger[counts.length];
		int position = 0;
		for (int i = 0; i < counts.length; i++) {
			if(mSections[i] == null) {
				mSections[i] = "";
			} else {
				mSections[i] = mSections[i].trim(); 
			}
			
			mPositions[i] = position;
			IndexerRanger indexerRanger =	new IndexerRanger();
			indexerRanger.start = position;
			position += counts[i];
			indexerRanger.end = (position-1)<indexerRanger.start?indexerRanger.start:(position-1);
			mIndexerRangers[i] = indexerRanger;
			
		}
		mCount = position;
		buildedIdx = true;
	}
	
	@Override
	public Object[] getSections() {
		// TODO Auto-generated method stub
		return mSections;
	}

	@Override
	public int getPositionForSection(int section) {
		if (section < 0 || section >=mSections.length) {
			return -1;
		}
		try{
			return mPositions[section];
		}catch(Exception e){
			CorePreferences.ERROR("mPositions[section]"+section);
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public int getSectionForPosition(int position) {
		while(!buildedIdx){
			try {
				Thread.currentThread().sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		if (position < 0 || position >= mCount) {
			return -1;
		}
		//注意这个方法的返回值，它就是index<0时，返回-index-2的原因
		//解释Arrays.binarySearch，如果搜索结果在数组中，刚返回它在数组中的索引，如果不在，刚返回第一个比它大的索引的负数-1
		//如果没弄明白，请自己想查看api
		int index = Arrays.binarySearch(mPositions, position);
		return index >= 0 ? index : -index - 2; //当index小于0时，返回-index-2，
		
	}
	public IndexerRanger getIndexerRanger(int section){
		if (section < 0 || section > mSections.length) {
			return null;
		}
		return mIndexerRangers[section];
		
	}
}
